package com.hl.mystudy.widget;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.RequiresApi;

import com.hl.mystudy.R;
import com.hl.mystudy.ui.home.ui.okhttp.OkHttpStudyActivity;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author hyhdez
 * @des ClockService 时钟服务
 * @date 2023/12/16 13:52
 */
public class ClockService extends Service {
    private static final String TAG = ClockService.class.getSimpleName();

    ScheduledExecutorService scheduledService;

    private final DateTimeFormatter weekSdf = DateTimeFormatter.ofPattern("EEEE");
    private final DateTimeFormatter timeSdf = DateTimeFormatter.ofPattern("HH:mm:ss");
    private final DateTimeFormatter dateSdf = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private ScreenOnReceiver receiver;
    private PowerManager pm;
    private BroadcastReceiver mBR;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        BasicThreadFactory factory = new BasicThreadFactory
                .Builder()
                .namingPattern("example-schedule-pool-%d")
                .daemon(true).build();
        scheduledService = new ScheduledThreadPoolExecutor(2, factory);
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        registerScreenReceiver();

        startBeforeNotification();

        scheduledService.scheduleAtFixedRate(() -> {
            boolean isScreenOn = pm.isInteractive();
            if (isScreenOn) {
                updateView();
            }
        }, 0, 1000, TimeUnit.MILLISECONDS);
    }

    private void registerScreenReceiver() {
        receiver = new ScreenOnReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(Intent.ACTION_BOOT_COMPLETED);
        registerReceiver(receiver, filter);
    }

    /**
     * 更新事件的方法
     */
    private void updateView() {
        // 时间
        LocalDateTime dateTime = LocalDateTime.now();
        String date = dateTime.format(dateSdf);
        String time = dateTime.format(timeSdf);
        String week = dateTime.format(weekSdf);
        String timeString = time + "\n" +
                date + "\n" +
                week;

        // 參数：1.包名2.小组件布局
        RemoteViews rViews = new RemoteViews(getPackageName(),
                R.layout.clock_app_widget);
        // 显示当前事件
        rViews.setTextViewText(R.id.appwidget_text, timeString);

        // 刷新
        AppWidgetManager manager = AppWidgetManager.getInstance(getApplicationContext());
        ComponentName cName = new ComponentName(getApplicationContext(),
                ClockAppWidgetProvider.class);
        manager.updateAppWidget(cName, rViews);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "服务被杀死");
        super.onDestroy();
        scheduledService.shutdown();
        unregisterReceiver(receiver);
    }

    @SuppressLint("ObsoleteSdkInt")
    private void startBeforeNotification() {
        Intent intent = new Intent(this, OkHttpStudyActivity.class);
        PendingIntent pendingIntent;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 123, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 123, intent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
        }

        String channelId = null;
        // 8.0 以上需要特殊处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channelId = createNotificationChannel("kim.hsl", "ForegroundService");
        } else {
            channelId = "";
        }

        Notification notification = new Notification.Builder(this)
                .setContentTitle("这是内容标题")
                .setContentText("这是内容正文")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .setContentIntent(pendingIntent)
                .setChannelId(channelId)
                .build();
        //前台服务
        startForeground(1, notification);

    }

    /**
     * 创建通知通道
     * @param channelId
     * @param channelName
     * @return
     */
    @RequiresApi(Build.VERSION_CODES.O)
    private String createNotificationChannel(String channelId, String channelName){
        NotificationChannel chan = new NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        service.createNotificationChannel(chan);
        return channelId;
    }

}
